package com.lznAdmin.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lznAdmin.base.lznAdminResult;
import com.lznAdmin.system.dto.PassWordDto;
import com.lznAdmin.system.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @program: lzn-manage-parent
 * @description: 用户管理
 * @author: lzn
 * @create: 2021-09-01 14:24
 **/
@Slf4j
@Api(tags = {"用户管理接口"})
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 分页：用户列表数据
     *
     * @param getUserAll 1获取全部用户信息
     * @param user       搜索条件
     * @return
     */
    @ApiOperation(value = "用户列表数据")
    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("/list")
    public lznAdminResult getUserData(SysUser user,
                                      @RequestParam(name = "current", defaultValue = "1") Integer current,
                                      @RequestParam(name = "size", defaultValue = "10") Integer size,
                                      @RequestParam(name = "getUserAll", defaultValue = "0") Integer getUserAll) {
        // log.info(JSON.toJSONString(page));
        if (getUserAll == 1) {
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.eq("is_enabled", true);
            return lznAdminResult.ok(sysUserService.list(sysUserQueryWrapper));
        }
        Page<SysUser> page = new Page<>(current, size);
        log.info("pageCurrent = {}", page.getCurrent());
        log.info("user: " + user);
        return lznAdminResult.ok(sysUserService.selectUserPage(page, user));
    }

    /**
     * 新增用户
     *
     * @param user
     * @param
     * @return
     */
    @ApiOperation(value = "新增用户")
    @PreAuthorize("hasAuthority('sys:user:save')")
    @PostMapping("/save")
    public lznAdminResult addUser(@Validated @RequestBody SysUser user) {
        log.info("user={}", user.toString());
        if (ObjectUtil.isEmpty(user.getPassword())) {
            String encode = passwordEncoder.encode("12345");
            user.setPassword(encode);
        }
        try {
            boolean b = sysUserService.addUserAndRole(user);
            if (b) {
                return lznAdminResult.ok("保存成功！");
            }
        } catch (Exception e) {
            log.error(e.getCause().getMessage());
            return lznAdminResult.no(e.getCause().getMessage());
        }
        return lznAdminResult.no("保存失败！");
    }


    /**
     * 编辑用户
     *
     * @param
     * @return
     */
    @ApiOperation(value = "编辑用户")
    @PreAuthorize("hasAuthority('sys:user:update')")
    @PutMapping("/edit")
    public lznAdminResult doEditUser(@Validated @RequestBody SysUser sysuser) throws Exception {
        Boolean aBoolean = sysUserService.editUserAndRole(sysuser);
        if (aBoolean) {
            return lznAdminResult.ok("保存成功！");
        }
        return lznAdminResult.no("保存失败！");
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/del")
    public lznAdminResult doAdminDelete(@RequestBody SysUser sysUser) {
        log.info("doAdminDelete = {}", sysUser);
        boolean b = sysUserService.deleteUserAndRole(sysUser.getId());
        if (b) {
            return lznAdminResult.ok("删除成功！");
        }
        return lznAdminResult.no("删除失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "修改用户密码")
    @PreAuthorize("hasAuthority('sys:user:update')")
    @PutMapping("/changePwd")
    public lznAdminResult changePassword(@Validated @RequestBody PassWordDto passWordDto) {

        log.info("passWordDto = {}", passWordDto);
        SysUser byUsername = sysUserService.findByUsername(passWordDto.getUsername());
        byUsername.setPassword(passwordEncoder.encode(passWordDto.getPassword()));
        boolean b = sysUserService.updateById(byUsername);
        if (b) {
            // 尝试清除修改密码的用户JWT
            jwtUtil.delLoginList(byUsername.getUsername());
            return lznAdminResult.ok("保存成功！");
        }
        return lznAdminResult.no("保存失败！");
    }
}
